﻿using System;
using System.Collections.Generic;
using System.Text;

namespace XAJH
{
    public class GraphicsHelper
    {
        /// <summary>
        /// 获取指定窗口的客户区域或整个屏幕的显示设备上下文环境的句柄
        /// </summary>
        /// <param name="hWnd"> 设备上下文环境被检索的窗口的句柄，如果该值为NULL，GetDC则检索整个屏幕的设备上下文环境。 </param>
        /// <returns></returns>
        [System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "GetDC")]
        internal extern static IntPtr GetDC(IntPtr hWnd);

        /// <summary>
        /// 释放设备上下文环境（DC）供其他应用程序使用。
        /// </summary>
        /// <param name="hWnd"> 指向要释放的设备上下文环境所在的窗口的句柄。 </param>
        /// <param name="hdc"> 指向要释放的设备上下文环境的句柄。 </param>
        /// <returns></returns>
        [System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "ReleaseDC")]
        internal extern static bool ReleaseDC(IntPtr hWnd, IntPtr hdc);

        /// <summary>
        /// 
        /// </summary>
        /// <param name="hdc"></param>
        /// <param name="nXPos"></param>
        /// <param name="nYPos"></param>
        /// <returns></returns>
        [System.Runtime.InteropServices.DllImport("gdi32", EntryPoint = "GetPixel")]
        internal extern static int GetPixel(IntPtr hdc, int nXPos, int nYPos);

        public static System.Drawing.Color GetColor(IntPtr hWnd, int x, int y)
        {
            return GetColor(hWnd, new System.Drawing.Point(x, y));
        }

        /// <summary>
        /// 获坐标点颜色
        /// </summary>
        /// <param name="hWnd"></param>
        /// <param name="point"></param>
        /// <returns></returns>
        public static System.Drawing.Color GetColor(IntPtr hWnd, System.Drawing.Point point)
        {
            IntPtr hdc = GetDC(hWnd);
            System.Windows.Forms.Application.DoEvents();
            int colorRef = GetPixel(hdc, point.X, point.Y);
            ReleaseDC(hWnd, hdc);
            System.Drawing.Color color = System.Drawing.Color.FromArgb(
            (int)(colorRef & 0x000000FF),
            (int)(colorRef & 0x0000FF00) >> 8,
            (int)(colorRef & 0x00FF0000) >> 16);
            return color;
        }

        /// <summary>
        /// 获取RGB 红色
        /// </summary>
        /// <param name="hWnd"> 窗口句柄 </param>
        /// <param name="x"> 横坐标 </param>
        /// <param name="y"> 纵坐标 </param>
        /// <returns></returns>
        public static byte GetColor_R(IntPtr hWnd, int x, int y)
        {
            return GetColor(hWnd, new System.Drawing.Point(x, y)).R;
        }

        /// <summary>
        /// 获取RGB 蓝色
        /// </summary>
        /// <param name="hWnd"> 窗口句柄 </param>
        /// <param name="x"> 横坐标 </param>
        /// <param name="y"> 纵坐标 </param>
        /// <returns></returns>
        public static byte GetColor_B(IntPtr hWnd, int x, int y)
        {
            return GetColor(hWnd, new System.Drawing.Point(x, y)).B;
        }
    }
}
